package com.example.exam.config;

import com.example.exam.entity.Role;
import com.example.exam.service.RoleService;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.annotation.Resource;
import java.util.List;

@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private RoleService roleService;

    //授权
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.headers().frameOptions().disable();
        httpSecurity.authorizeRequests()
                .antMatchers("/login.html").permitAll()
                .antMatchers("/css/**").permitAll()
                .antMatchers("/images/**").permitAll()
                .antMatchers("/js/**").permitAll()
                .antMatchers("/reg.html").permitAll()
                .antMatchers("/completeReg").permitAll()
                .antMatchers("/admin/**").permitAll()
                .antMatchers("/message/insertMess").permitAll()
                .antMatchers("/student/**").hasRole("student")
                .antMatchers("/teacher/**").hasRole("teacher")
                .antMatchers("/assist/**").hasRole("assist")
                .antMatchers("/admin/**").hasRole("admin")
                .anyRequest().authenticated()
                .and()
                .formLogin()
                //指定登录页的路径
                .loginPage("/index.html")
                //指定自定义form表单请求的路径
                .loginProcessingUrl("/loginPost")
                .defaultSuccessUrl("/loginPost")
                .successForwardUrl("/loginPost")
                //必须允许所有用户访问我们的登录页（例如未验证的用户，否则验证流程就会进入死循环）
                //这个formLogin().permitAll()方法允许所有用户基于表单登录访问/login这个page。
                .permitAll();
        //默认都会产生一个hiden标签 里面有安全相关的验证 防止请求伪造 这边我们暂时不需要 可禁用掉
        httpSecurity.csrf().disable();
    }


    //认证
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        List<Role> roles = roleService.queryByAll();
        for (Role role : roles) {
            if ("teacher".equals(role.getPerms())) {
                auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                        .withUser(role.getroleName()).password(new BCryptPasswordEncoder().encode(role.getPassword())).roles("teacher");
            } else if ("assist".equals(role.getPerms())) {
                auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                        .withUser(role.getroleName()).password(new BCryptPasswordEncoder().encode(role.getPassword())).roles("assist");
            } else if ("student".equals(role.getPerms())) {
                auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                        .withUser(role.getroleName()).password(new BCryptPasswordEncoder().encode(role.getPassword())).roles("student");
            } else if ("admin".equals(role.getPerms())) {
                auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                        .withUser(role.getroleName()).password(new BCryptPasswordEncoder().encode(role.getPassword())).roles("admin");
            }
        }
    }

//    public void configure(WebSecurity web) throws Exception {
//        //解决静态资源被SpringSecurity拦截的问题
//        web.ignoring().antMatchers("/static/**");//这样我的webapp下static里的静态资源就不会被拦截了，也就不会导致我的网页的css全部失效了……
//    }
}